#include "ota_http.h"
#include "log/log.h"
#include <curl/curl.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

/**
 * 接收响应数据的回调函数
 * ptr: 指向响应数据的指针
 * size: 每个数据块的大小
 * nmemb: 数据块的数量
 * 
 */
static size_t ota_http_write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{
    char *json_buf = (char *)userdata;
    int json_len = size * nmemb;
    memcpy(json_buf, ptr, json_len);
    json_buf[json_len] = '\0';
    return json_len;
}
/**
 * 请求获取得到json数据
 */
char *ota_http_getJSON(char *url)
{
    //curl init
    CURL *curl = curl_easy_init();
    //set url option
    curl_easy_setopt(curl, CURLOPT_URL, url);
    //set receive data callback
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ota_http_write_callback);
    //set receive data buffer
    char *json_buf = (char *)malloc(1024);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, json_buf);
    //send request
    CURLcode res = curl_easy_perform(curl);
    //check response
    if (res != CURLE_OK)
    {
        log_error("ota_http_getJSON() failed: %s\n", curl_easy_strerror(res));
        free(json_buf);
        curl_easy_cleanup(curl);
        return NULL;
    }
    //request success
    curl_easy_cleanup(curl);
    return json_buf;
}
/**
 * 下载文件
 */
int ota_http_download(char *url, char *filename)
{
    /// 初始化CURL
    CURL *curl = curl_easy_init();
    // 指定url
    curl_easy_setopt(curl, CURLOPT_URL, url);
    // 指定得到返回的文件的回调函数
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);
    // 指定得到返回的文件的回调函数的参数
    FILE *fp = fopen(filename, "wb");
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
    // 执行请求
    CURLcode res = curl_easy_perform(curl);
    // 如果请求失败，释放资源，返回-1
    if (res != CURLE_OK) {
        log_error("ota_http_download failed: %s", curl_easy_strerror(res));
        fclose(fp);
        curl_easy_cleanup(curl);
        return -1;
    }
    // 请求成功，释放资源
    fclose(fp);
    curl_easy_cleanup(curl);
    return 0;
}
